package com.itboye.hutouben.activity.mysetting;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.itboye.hutouben.R;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.base.MyApplcation;
import com.itboye.hutouben.presenter.UserPresenter;
import com.itboye.hutouben.util.ByAlert;
import com.itboye.hutouben.util.CameraPopupWindow;
import com.itboye.hutouben.util.Const;
import com.itboye.hutouben.util.ImageCompress;
import com.itboye.hutouben.util.IsUtilUid;
import com.itboye.hutouben.util.MultipartRequest;
import com.itboye.hutouben.util.MyGongJv;
import com.itboye.hutouben.util.SPUtils;
import com.itboye.hutouben.volley.ResultEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 司机认证
 */
public class DriverRenZhengActivity extends BaseActivity implements Observer {
    EditText driver_name, driver_code;
    TextView add_shap_title_tv;
    ImageView close_icon;
    TextView ok;
    ImageView update_up, update_down, driver_update;//身份证正面，背面，驾驶证

    /**
     * 使用相机拍照（正面）
     */
    private static final int REAL_PHONE = 1;
    /**
     * 使用相机拍照（背面）
     */
    private static final int REAL_PHONE_TWO = 3;
    /**
     * 身份证正面的选择
     */
    private String localSelectPath01;
    /**
     * 身份证背面的选择
     */
    private String localSelectPath02;
    /**
     * 驾驶证
     */
    private String localSelectPath03;
    private String type;
    ImageView real_img01, real_img02, real_img03;
    private String fileName01;

    CameraPopupWindow mCameraPopupWindow;

    String zhengID, fanID, jiaID;//正面图片上传成功之后的Id,反面id，驾驶证id

    UserPresenter presenter;
    String uid;
    TextView tvzheng1, tvzheng2, tvzheng3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver_ren_zheng);
        add_shap_title_tv.setText("司机认证");
        presenter = new UserPresenter(this);

    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    private String picture_name;

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REAL_PHONE:// 相机
                    Bitmap bit = BitmapFactory.decodeFile(fileName);
                    if (type != null) {
                        if (type.equals("zheng")) {
                            localSelectPath01 = ImageCompress.compress(fileName);
                            onImage(localSelectPath01);
                            tvzheng1.setVisibility(View.GONE);
                            update_up.setImageBitmap(bit);
                        } else if (type.equals("fan")) {
                            localSelectPath02 = ImageCompress.compress(fileName);
                            onImage(localSelectPath02);
                            tvzheng2.setVisibility(View.GONE);
                            update_down.setImageBitmap(bit);
                        } else {
                            localSelectPath03 = ImageCompress.compress(fileName);
                            onImage(localSelectPath03);
                            tvzheng3.setVisibility(View.GONE);
                            driver_update.setImageBitmap(bit);
                        }
                    }
                    mCameraPopupWindow.dismiss();
                    break;

                case REAL_PHONE_TWO:// 相册
                    /**
                     * 当选择的图片不为空的话，在获取到图片的途径
                     */
                    Uri selectedImage04 = data.getData();
                    String innerUrl = getRealPathFromURI(selectedImage04);
                    if (type != null) {
                        if (type.equals("zheng")) {
                            localSelectPath01 = ImageCompress.compress(innerUrl);
                            onImage(localSelectPath01);
                            tvzheng1.setVisibility(View.GONE);
                        } else if (type.equals("fan")) {
                            localSelectPath02 = ImageCompress.compress(innerUrl);
                            onImage(localSelectPath02);
                            tvzheng2.setVisibility(View.GONE);
                        } else {
                            localSelectPath03 = ImageCompress.compress(innerUrl);
                            onImage(localSelectPath03);
                            tvzheng3.setVisibility(View.GONE);
                        }
                    }

                    Bitmap bt04 = BitmapFactory.decodeFile(innerUrl);
                    if (type != null) {
                        if (type.equals("zheng")) {
                            update_up.setImageBitmap(bt04); // 把图片显示在ImageView控件上
                        } else if (type.equals("fan")) {
                            update_down.setImageBitmap(bt04);
                        } else {
                            driver_update.setImageBitmap(bt04);
                        }
                    }
                    mCameraPopupWindow.dismiss();
                    break;

                default:
                    break;
            }
        }

    }

    public void onImage(String str) {
        showProgressDialog("上传中....", true);
        File files = new File(str);
        if (str == null) {
            ByAlert.alert("请上传图片");
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("uid", IsUtilUid.isUid());
        String leixing = "";
        if (type.equals("jia")) {
            leixing = "driver_cert";
        } else {
            leixing = "id_certs";
        }
        params.put("type", leixing);

        MultipartRequest multipartRequest = new MultipartRequest(
                Const.IMAGE_URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String arg0) {
                        Log.d("urlTime", arg0.toString());

                        allInfoFromJson(arg0.toString());

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                ByAlert.alert(arg0);
            }
        }, "image", files, params);
        MyApplcation.addRequest(multipartRequest);

    }

    public void allInfoFromJson(String jsonStr) {

        try {
            JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                if (type.equals("zheng")) {
                    zhengID = jsonObject.getString("id");
                } else if (type.equals("fan")) {
                    fanID = jsonObject.getString("id");
                } else {
                    jiaID = jsonObject.getString("id");
                }
                String busName = jsonObject.getString("id");
                Log.d("busLin", busName);
                String time = String.valueOf((int) (Math.random() * 10));
                ByAlert.alert("上传成功!");
                try {
                    closeProgressDialog();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ByAlert.alert("上传失败!");
            try {
                closeProgressDialog();
            } catch (Exception d) {
                // TODO: handle exception
            }
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.update_up:
                type = "zheng";
                mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                MyGongJv.yincang(v);
                break;
            case R.id.update_down:
                type = "fan";
                mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                MyGongJv.yincang(v);
                break;
            case R.id.driver_update:
                type = "jia";
                mCameraPopupWindow = new CameraPopupWindow(this, onclicklister01);
                mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                MyGongJv.yincang(v);
                break;
            case R.id.ok:
//                intent=new Intent(this,RenZhengInformationActivity.class);
//                startActivity(intent);
                uid = (String) SPUtils.get(this, null, Const.ID, "");
                String name = driver_name.getText().toString();
                String code = driver_code.getText().toString();
                if (name == "" || name == null) {
                    ByAlert.alert("请输入真实姓名");
                    return;
                }
                if (code == "" || code == null) {
                    ByAlert.alert("请输入身份证号码");
                    return;
                }
                if (code.length() != 18) {
                    ByAlert.alert("请输入身份证号码");
                    return;
                }
                Log.d("zhengID", zhengID + "");
                if (zhengID == "" || zhengID == null) {
                    ByAlert.alert("请先上传身份证");
                    return;
                }
                if (fanID == "" || fanID == null) {
                    ByAlert.alert("请先上传身份证");
                    return;
                }
                if (jiaID == "" || jiaID == null) {
                    ByAlert.alert("请上传驾驶证");
                    return;
                }
                StringBuffer sb = new StringBuffer();
                sb.append(zhengID + ",");
                sb.append(fanID);
                showProgressDialog("请稍后...", true);
                presenter.sijiRenZheng(uid, code, name, sb.toString(), jiaID);


                break;
        }
    }

    private String fileName;
    /**
     * 正面
     */
    private View.OnClickListener onclicklister01 = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.open_camera:
                    /**
                     * 打开照相机
                     */
                    picture_name = android.text.format.DateFormat.format(
                            "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
                            + ".jpg";
                    File file = new File("/sdcard/Image/");
                    file.mkdirs();// 创建文件夹
                    fileName = "/sdcard/Image/" + picture_name;
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(fileName)));
                    startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);

                    mCameraPopupWindow.dismiss();

                    break;
                case R.id.pick_image:
                    Intent intent2 = new Intent();
                    intent2.setType("image/*");// 可选择图片视频
                    // 修改为以下两句代码
                    intent2.setAction(Intent.ACTION_PICK);
                    intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
                    startActivityForResult(intent2, REAL_PHONE_TWO);
                    mCameraPopupWindow.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 该方法用于获取文件的真实路径从URI 从相机拍摄
     */
    private String getRealPathFromURI(Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = this.managedQuery(contentUri, proj, null, null,
                    null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == UserPresenter.renzheng_success) {
                ByAlert.alert(entity.getData());

                SPUtils.put(DriverRenZhengActivity.this, null,
                        Const.ISAUTH, "2");

                Intent intent1 = new Intent("ISAUTH");
                sendBroadcast(intent1);

                finish();

            } else if (entity.getEventType() == UserPresenter.renzheng_fail) {
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
}
